package com.qf.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 王博康
 * @version 1.0
 * @project webSocketDemo
 * @description: TODO
 * @date 2022/3/26 13:53 星期六
 */
@Component
public class MyWebSocket extends TextWebSocketHandler {

    private static HashMap<String,WebSocketSession> allConn=new HashMap<>();

    private ObjectMapper objectMapper=new ObjectMapper();

    /**
     * 当有人连接成功后执行
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.err.println("有人创建连接啦"+session.getId());
        //获取请求路径
        String uri = session.getUri().toString();
        //截取路径后边的用户名
        String username = uri.substring(uri.lastIndexOf("/") + 1);
        //将用户名保存到会话中,方便之后使用
        session.getAttributes().put("username",username );
        //将会话保存到缓存,用户名做key
        allConn.put(username,session );
    }

    /**
     * 数据连接出现错误时运行
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    /**
     * 当有连接发生消息时运行
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.err.println("有人给服务器发消息了-->"+message.getPayload()+"<--"+session.getId());
        //处理收到信息
        //1 获取信息
        String payload = message.getPayload();
        //2 解析信息
        Map<String,String> map = objectMapper.readValue(payload, Map.class);
        String touser = map.get("toUser");
        String msg = map.get("msg");
        //3 从缓存中获得对方会话
        WebSocketSession webSocketSession = allConn.get(touser);
        //4 如果对方会话为空或已经关闭,回复 对方离线
        if (webSocketSession==null||!webSocketSession.isOpen()){
            session.sendMessage(new TextMessage("对方离线"));
            return;
        }
        //5 给对方发转发信息
        String username = (String) session.getAttributes().get("username");
        webSocketSession.sendMessage(new TextMessage(username+" 给您发送消息:"+msg));
    }

    /**
     * 当有连接断开时运行
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.err.println("有人断开连接了"+session.getId());
        //从缓存中移除会话
        allConn.remove(session.getAttributes().get("username"));
    }
}
